<?php
/* -----------------------------------------------------------------
 *                          Aveghe Installer
 * -----------------------------------------------------------------
 * Aveghe Installer: made your web application installation easy!
 * Copyright (C) 2008 Elia Contini
 * 
 * Aveghe Installer is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * Aveghe Installer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 */

error_reporting (E_STRICT);
set_include_path(get_include_path().PATH_SEPARATOR.'../lib');
date_default_timezone_set('Europe/Rome');

require_once('Zend/Loader.php');
require_once('Aveghe/SQLReader.php');

Zend_Loader::registerAutoload();

// session starts
$avegheNS = new Zend_Session_Namespace('avegheNS');

if($_SERVER['REQUEST_METHOD'] == 'GET')
	{
		header('Location: index.php');
		exit;
	}

$domain        = (string) $_POST['domain'];
$dbHost        = (string) $_POST['dbHost'];
$dbUsername    = (string) $_POST['dbUsername'];
$dbPassword    = (string) $_POST['dbPassword'];
$dbName        = (string) $_POST['dbName'];
$dbTablePrefix = (string) $_POST['dbTablePrefix'];

// parameter test here
$report = array();
if($domain == '')
	$report['message'] .= '<p class="warning">Devi specificare il dominio sui verr&agrave; installato Aveghe My Blog.</p>';
if($dbHost == '')
	$report['message'] .= '<p class="warning">Devi specificare l\'indirizzo del server MySQL.</p>';
if($dbUsername == '')
	$report['message'] .= '<p class="warning">Devi specificare l\'utente del server MySQL.</p>';
if($dbPassword == '')
	$report['message'] .= '<p class="warning">Devi specificare la password per il server MySQL.</p>';
if($dbName == '')
	$report['message'] .= '<p class="warning">Devi specificare il nome del data base.</p>';
	
if($report['message'] != '')
	{
		$report['domain'] = $domain;
		$report['dbHost'] = $dbHost;
		$report['dbUsername'] = $dbUsername;
		$report['dbName'] = $dbName;
		$report['dbTablePrefix'] = $dbTablePrefix;
		
		$avegheNS->report = $report;
		
		header('Location: index.php');
		exit;
	}

$parameters = array(
					'host'     => $dbHost,
     				'username' => $dbUsername,
    				'password' => $dbPassword,
    				'dbname'   => $dbName,
				   );

$theme = "resources/themes/aveghe/template.xhtml";
$meta = "<meta http-equiv=\"Content-Type\" content=\"application/xhtml+xml; charset=UTF-8\" />\n";

if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml")) 
	header("Content-type: application/xhtml+xml");
else
	{
		header("Content-type: text/html");
		$meta = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n";
	}

$fileCreated = false;
$schemaInstalled = false;

try
	{
		// schema installation
    	$db = Zend_Db::factory('Pdo_Mysql', $parameters);
    	
    	$sqlReader = new Aveghe_SQLReader('resources/sql/mysql_schema.sql', $dbTablePrefix);
    	$queries = $sqlReader->getQueriesArray();

    	for($i = 0; $i < count($queries); $i++)
    		{
    			$db->getConnection()->exec($queries[$i]);
    		}
    	
    	// save preferences
    	$preferences = array( 'site_domain'           => $domain,
    						  'site_language'         => 'it-IT',
    						  'site_admin_theme'      => 'default',
    						  'site_public_theme'     => 'default',
    						  'site_home_item_num'    => '10',
    						  'site_rss_item_num'     => '10',
    						  'site_upload_directory' => 'img'
    						);
    	$db->insert($dbTablePrefix.'preferences', $preferences);
    	
    	$db->closeConnection();
    	
    	$schemaInstalled = true;
    	
    	// configuration file
		// content of config file
		$fileContent  = "<?php\n"; // open php script
		$fileContent .= "/* Aveghe My Blog - Configuration file\n";
		$fileContent .= " *\n";
		$fileContent .= " * Generated by Aveghe Installer at ".date("F j, Y, g:i a")."\n";
		$fileContent .= " */\n\n";
		$fileContent .= "define('DATABASE_HOST'        , '".$dbHost."');\n";
		$fileContent .= "define('DATABASE_NAME'        , '".$dbName."');\n";
		$fileContent .= "define('DATABASE_USERNAME'    , '".$dbUsername."');\n";
		$fileContent .= "define('DATABASE_PASSWORD'    , '".$dbPassword."');\n";
		$fileContent .= "define('DATABASE_TABLE_PREFIX', '".$dbTablePrefix."');\n";
		$fileContent .= "define('THEME'                , 'aveghe');\n\n";
		
		$baseURL = str_replace('installer/install.php','',$_SERVER['PHP_SELF']);
		$baseURL = substr($baseURL, 0, strlen($baseURL) - 1);
		$fileContent .= "define('BASE_URL'             , '$baseURL');\n"; 
		$fileContent .= '?>'; //close php script
		
		if(file_exists('../aveghe/conf') && is_dir('../aveghe/conf') && is_writable('../aveghe/conf'))
			{
				$handler = fopen('../aveghe/conf/conf.php', 'w');
				fputs($handler, $fileContent);
				fclose($handler);
				
				$fileCreated = true;
			}
		
		if(!$fileCreated)
			$avegheNS->fileContent = $fileContent;
	}
catch (Zend_Db_Adapter_Exception $e)
	{
    	// perhaps a failed login credential, or perhaps the RDBMS is not running
    	print($e->getMessage());
	}
catch (Zend_Exception $e)
	{
    	// perhaps factory() failed to load the specified Adapter class
    	print($e->getMessage());
	}

$content = <<< CONTENT

	<h2>Rapporto</h2>
	
CONTENT;

if($schemaInstalled)
	$content .= "<p class=\"success\">Database creato con successo.</p>\n";
else
	$content .= "<p class=\"fail\">Il database non &egrave; stato installato corretamente.</p>\n";

if($fileCreated)
	$content .= "<p class=\"success\">File di configurazione creato con successo.</p>\n";
else
	$content .= "<p class=\"warning\">Non &egrave; stato possibile salvare il file di configurazione. Per completare correttamente l'installazione <a href=\"dlConfFile.php\" title=\"Scarica il file di configurazione.\">scaricalo</a> e copialo nella directory <strong>conf</strong>.</p>\n";	

if($schemaInstalled)
	$content .= <<< CONTENT
		<p>Per iniziare ad usare aveghe MyBlog <a href="createUserForm.php" title="Crea un utente.">crea un utente</a>.</p>
CONTENT;
	
include($theme);
?>